package com.liuyjy.encryptDecrypt;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.BeanDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBase;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.io.IOException;
import java.util.List;

/**
 * @Author liuyjy
 * @Date 2025/2/21 9:40
 * @Description: 对象属性加解密
 **/
public class CryptoBeanDeserializerModifier extends BeanDeserializerModifier {
    private final CryptoProvider provider;

    public CryptoBeanDeserializerModifier(CryptoProvider provider) {
        this.provider = provider;
    }

    @Override
    public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                  BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
        List<BeanPropertyDefinition> props = beanDesc.findProperties();
        for (BeanPropertyDefinition prop : props) {
            Decrypt decrypt = prop.getField().getAnnotation(Decrypt.class);
            Encrypt encrypt = prop.getField().getAnnotation(Encrypt.class);

            if (decrypt != null) {
                return new DynamicCryptoDeserializer(provider, decrypt);
            }
            if (encrypt != null) {
                return new DynamicCryptoDeserializer(provider, encrypt);
            }
        }
        return deserializer;
    }
}